from algorithm import Algorithm
import math

class DetailEnhancement(Algorithm):
    def __init__(self):
        super(DetailEnhancement)
        self.factor = 2.0
        self.kernel_size = 1
        
    def perform_action(self):
        for i in range(1, len(self.pixels)-1):
            for j in range(1, len(self.pixels[i])-1):
                kern_r = []
                kern_g = []
                kern_b = []
                for k in range(i-self.kernel_size, i + self.kernel_size + 1):
                    for l in range(j - self.kernel_size, j + self.kernel_size + 1):
                        kern_r.append(self.pixels[k][l][0])
                        kern_g.append(self.pixels[k][l][1])
                        kern_b.append(self.pixels[k][l][2])
                kern_r.sort()
                kern_g.sort()
                kern_b.sort()
                r = self.pixels[i][j][0] + (self.pixels[i][j][0] - kern_r[5]) * abs(kern_r[1] - kern_r[8]) * self.factor
                g = self.pixels[i][j][1] + (self.pixels[i][j][1] - kern_g[5]) * abs(kern_g[1] - kern_g[8]) * self.factor
                b = self.pixels[i][j][2] + (self.pixels[i][j][2] - kern_b[5]) * abs(kern_b[1] - kern_b[8]) * self.factor
                if r > 255:
                    r = 255
                if g > 255:
                    g = 255
                if b > 255:
                    b = 255
                self.pixels[i][j] = (int(r), int(g), int(b))